﻿using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Organizations;
using AbpProject.Organization.Dto;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Abp.UI;
using Abp.Application.Services.Dto;

namespace AbpProject.Organization
{
    public class OrganizationUnitAppService : AbpProjectAppServiceBase, IOrganizationUnitAppService
    {
        private readonly OrganizationUnitManager _organizationUnitManager;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
        //private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;


        public OrganizationUnitAppService(
             OrganizationUnitManager organizationUnitManager,
             IRepository<OrganizationUnit, long> organizationUnitRepository,
             IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository
            )
        {
            _organizationUnitManager = organizationUnitManager;
            _organizationUnitRepository = organizationUnitRepository;
            _userOrganizationUnitRepository = userOrganizationUnitRepository;
        }

        /// <summary>
        /// 创建组织架构
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task Create(OrganizationUnitDto input)
        {
            var isContains = await _organizationUnitRepository.FirstOrDefaultAsync(r => r.Code.Equals(input.Code));
            if (isContains != null)
            {
                throw new UserFriendlyException("代码已存在!");
            }
            await _organizationUnitManager.CreateAsync(input.MapTo(new OrganizationUnit()));
        }

        /// <summary>
        /// 修改组织架构
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task Update(OrganizationUnitDto input)
        {
            var isContains = await _organizationUnitRepository.FirstOrDefaultAsync(r => r.Code.Equals(input.Code) && r.Id != input.Id);
            if (isContains != null)
            {
                throw new UserFriendlyException("代码已存在!");
            }
            await _organizationUnitManager.UpdateAsync(input.MapTo(new OrganizationUnit()));
        }

        /// <summary>
        /// 获取组织架构树
        /// </summary>
        /// <returns></returns>
        public async Task<ListResultDto<OrganizationUnitModel>> GetTree()
        {
            var list = await (from a in _organizationUnitRepository.GetAll().AsNoTracking()
                              select a.MapTo<OrganizationUnitDto>()).ToListAsync();
            var result = GetTreeParent(list);
            return new ListResultDto<OrganizationUnitModel>(result);
        }

        /// <summary>
        /// 获取用户的组织架构
        /// </summary>
        /// <returns></returns>
        public async Task<ListResultDto<OrganizationUnitModel>> GetUserTree()
        {
            var list = await (from a in _organizationUnitRepository.GetAll().AsNoTracking()
                              select a.MapTo<OrganizationUnitDto>()).ToListAsync();
            var result = GetTreeParent(list);
            return new ListResultDto<OrganizationUnitModel>(result);
        }

        /// <summary>
        /// 转化成树结构
        /// </summary>
        /// <param name="menuList">菜单的平级list</param>
        /// <returns></returns>
        private List<OrganizationUnitModel> GetTreeParent(List<OrganizationUnitDto> menuList)
        {
            var dic = new Dictionary<long, OrganizationUnitModel>(menuList.Count);
            foreach (var chapter in menuList)
            {
                dic.Add(chapter.Id, chapter.MapTo<OrganizationUnitModel>());
            }
            foreach (var chapter in dic.Values)
            {
                if (dic.ContainsKey(chapter.ParentId.Value))
                {
                    if (dic[chapter.ParentId.Value].Children == null)
                    {
                        dic[chapter.ParentId.Value].Children = new List<OrganizationUnitModel>();

                    }
                    dic[chapter.ParentId.Value].Children.Add(chapter);
                }
            }
            return dic.Values.Where(t => t.ParentId == 0).ToList();
        }


        /// <summary>
        /// 删除组织架构
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task Delete(EntityDto<long> input)
        {
            await _organizationUnitManager.DeleteAsync(input.Id);
        }


       
    }
}
